//
//  WDGroMoreInterstitialManager.m
//  WDGroMore
//
//  Created by little People on 2023/7/27.
//

//
//  WDGroMoreInterstitialManager.m
//  WDGroMore
//

#import "WDGroMoreInterstitialManager.h"
#import "WDGroMoreHeader.h"
#import "WDBMS.h"
@interface WDGroMoreInterstitialManager ()<BUMNativeExpressFullscreenVideoAdDelegate>
@property (nonatomic, strong) BUNativeExpressFullscreenVideoAd *intersititialAd;
@property (nonatomic, copy) NSString * userUUId;
@end

@implementation WDGroMoreInterstitialManager
static WDGroMoreInterstitialManager *_manager = nil;

+ (instancetype)manager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[self alloc] init];
    });
    return _manager;
}

- (void)createInterstitialAdWithPlacementId:(NSString *)placementId userId:(NSString *)userId {
    NSLog(@"[Interstitial] Create with placementId: %@, userId: %@", placementId, userId);
    self.userUUId = userId;
    BUAdSlot *slot = [[BUAdSlot alloc] init];
    slot.ID = placementId;
    slot.mediation.mutedIfCan = YES;
//    [slot.mediation addParam:@(0) withKey:@"show_direction"];

    BUNativeExpressFullscreenVideoAd *fullscreenAd = [[BUNativeExpressFullscreenVideoAd alloc] initWithSlot:slot];
    fullscreenAd.delegate = self;

    [BUAdSDKManager.mediation preloadAdsWithInfos:@[fullscreenAd] andInterval:2 andConcurrent:4];

    self.intersititialAd = fullscreenAd;
    [self.intersititialAd loadAdData];

    [WDGroMoreTrackManager track:BMS_EVENT_AD_REQUEST
                          params:@{BMS_PARAM_WDS:BMS_WDS_AD_REQUEST,
                                   BMS_PARAM_TAB1:@"",
                                   BMS_PARAM_TAB2:placementId ?: @""}
                           dType:BMS_DTYPE_AD_ACTION
                            desc:BMS_WDS_AD_REQUEST
                         options:[WDGroMoreTrackManager trackOptionsOnlySendBMS]];
}

- (void)showInterstitialdAd {
    NSLog(@"[Interstitial] Try to show ad");
//    [[WDGroMoreBmsReportManager manager] intersititialBmsEventWithEventName:BMS_EVENT_ad_button_click intersititialAd:self.intersititialAd];

    if (self.intersititialAd.mediation.isReady) {
        NSLog(@"[Interstitial] Ad is ready, show now");
        if ([WDGroMoreDelegateManager manager].delegate &&
            [[WDGroMoreDelegateManager manager].delegate respondsToSelector:@selector(WDGroMoreIntersititialAdShow:)]) {
            [[WDGroMoreDelegateManager manager].delegate WDGroMoreIntersititialAdShow:self.intersititialAd];
        }
        [self.intersititialAd showAdFromRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
    } else {
        NSLog(@"[Interstitial] Ad not ready, reload");
        if ([WDGroMoreDelegateManager manager].delegate &&
            [[WDGroMoreDelegateManager manager].delegate respondsToSelector:@selector(WDGroMoreIntersititialAdReady:)]) {
            [[WDGroMoreDelegateManager manager].delegate WDGroMoreIntersititialAdReady:self.intersititialAd.mediation.isReady];
        }
        [self intersititialAdLoad];
    }
}

- (void)intersititialAdLoad {
    NSLog(@"[Interstitial] Reload ad");
    [self createInterstitialAdWithPlacementId:[WDGroMoreJosnManager GroMoreInterstitialIdForSDKConfigFile] userId:self.userUUId];
}

#pragma mark - BUMNativeExpressFullscreenVideoAdDelegate

- (void)nativeExpressFullscreenVideoAdDidLoad:(BUNativeExpressFullscreenVideoAd *)intersititialAd {
    NSLog(@"✅ [Interstitial] Ad loaded successfully");
    NSDictionary *ritInfo = [WDGroMoreAdHelper ecpmInfoFromAd:intersititialAd];
    [WDGroMoreTrackManager track:BMS_EVENT_AD_FILL
                          params:@{BMS_PARAM_WDS:BMS_WDS_AD_FILL,
                                   BMS_PARAM_TAB1:ritInfo[@"adn"] ?: @"",
                                   BMS_PARAM_TAB2:ritInfo[@"ecpm"] ?: @"",
                                   BMS_PARAM_TAB3:ritInfo[@"slotID"] ?: @""}
                           dType:BMS_DTYPE_AD_ACTION
                            desc:BMS_WDS_AD_FILL
                         options:[WDGroMoreTrackManager trackOptionsOnlySendBMS]];
//    [[WDGroMoreBmsReportManager manager] intersititialBmsEventWithEventName:BMS_EVENT_ad_load_sucess intersititialAd:intersititialAd];
}

- (void)nativeExpressFullscreenVideoAd:(BUNativeExpressFullscreenVideoAd *)intersititialAd didFailWithError:(NSError *_Nullable)error {
    NSLog(@"❌ [Interstitial] Load failed: %@", error.localizedDescription);
}

- (void)nativeExpressFullscreenVideoAdDidClick:(BUNativeExpressFullscreenVideoAd *)intersititialAd {
    NSLog(@"👉 [Interstitial] Ad clicked");
    BUMRitInfo *ritInfo = [intersititialAd.mediation getShowEcpmInfo];
    [WDGroMoreTrackManager track:BMS_EVENT_AD_CLICK
                          params:@{BMS_PARAM_WDS:BMS_WDS_AD_CLICK,
                                   BMS_PARAM_TAB1:ritInfo.adnName ?: @"",
                                   BMS_PARAM_TAB2:ritInfo.slotID ?: @"",
                                   BMS_PARAM_TAB3:ritInfo.ecpm ?: @""}
                           dType:BMS_DTYPE_AD_ACTION
                            desc:BMS_WDS_AD_CLICK
                         options:[WDGroMoreTrackManager trackOptionsOnlySendBMS]];
}

- (void)nativeExpressFullscreenVideoAdWillVisible:(BUNativeExpressFullscreenVideoAd *)intersititialAd {
    NSLog(@"[Interstitial] Will visible");
//    [[WDGroMoreBmsReportManager manager] intersititialBmsEventWithEventName:BMS_EVENT_ad_show_start intersititialAd:intersititialAd];
}

- (void)nativeExpressFullscreenVideoAdDidVisible:(BUNativeExpressFullscreenVideoAd *)intersititialAd {
    NSLog(@"✅ [Interstitial] Did visible");
    BUMRitInfo *ritInfo = [intersititialAd.mediation getShowEcpmInfo];
    [WDGroMoreTrackManager track:BMS_EVENT_AD_IMPRESSION
                          params:@{BMS_PARAM_WDS:BMS_WDS_AD_SHOW,
                                   BMS_PARAM_TAB1:ritInfo.adnName ?: @"",
                                   BMS_PARAM_TAB2:ritInfo.slotID ?: @"",
                                   BMS_PARAM_TAB3:ritInfo.ecpm ?: @""}
                           dType:BMS_DTYPE_AD_ACTION
                            desc:BMS_WDS_AD_SHOW
                         options:[WDGroMoreTrackManager trackOptionsOnlySendBMS]];
    
    [[WDGroMoreThinkingManager manager]thinkingTrackEventWithKey:@"AD_Inter_show" jsonStr:@{BMS_PARAM_WDS:BMS_WDS_AD_SHOW,
                                                                                         BMS_PARAM_TAB1:ritInfo.adnName ?: @"",
                                                                                         BMS_PARAM_TAB2:ritInfo.slotID ?: @"",
                                                                                         BMS_PARAM_TAB3:ritInfo.ecpm ?: @""}];
    NSLog(@"ecpm: %@, platform: %@, slotID: %@, requestID: %@",
          ritInfo.ecpm, ritInfo.adnName, ritInfo.slotID, ritInfo.requestID ?: @"None");
}

- (void)nativeExpressFullscreenVideoAdDidClickSkip:(BUNativeExpressFullscreenVideoAd *)intersititialAd {
    NSLog(@"[Interstitial] User clicked skip");
//    [[WDGroMoreBmsReportManager manager] intersititialBmsEventWithEventName:BMS_EVENT_ad_show_skip intersititialAd:intersititialAd];
    if ([WDGroMoreDelegateManager manager].delegate &&
        [[WDGroMoreDelegateManager manager].delegate respondsToSelector:@selector(WDGroMoreIntersititialAdDidClickSkip:)]) {
        [[WDGroMoreDelegateManager manager].delegate WDGroMoreIntersititialAdDidClickSkip:intersititialAd];
    }
}

- (void)nativeExpressFullscreenVideoAdDidClose:(BUNativeExpressFullscreenVideoAd *)intersititialAd {
    NSLog(@"[Interstitial] Ad closed");
    if ([WDGroMoreDelegateManager manager].delegate &&
        [[WDGroMoreDelegateManager manager].delegate respondsToSelector:@selector(WDGroMoreIntersititialAdDelegateWithClose:)]) {
        [[WDGroMoreDelegateManager manager].delegate WDGroMoreIntersititialAdDelegateWithClose:intersititialAd];
    }
    [self intersititialAdLoad];
}

- (void)nativeExpressFullscreenVideoAdDidPlayFinish:(BUNativeExpressFullscreenVideoAd *)intersititialAd didFailWithError:(NSError *_Nullable)error {
    NSLog(@"[Interstitial] Play finished, error: %@", error.localizedDescription);
    BUMRitInfo *ritInfo = [intersititialAd.mediation getShowEcpmInfo];
    [WDGroMoreTrackManager track:BMS_EVENT_AD_IMPRESSION_DONE
                          params:@{BMS_PARAM_WDS:BMS_WDS_AD_FINISH,
                                   BMS_PARAM_TAB1:ritInfo.adnName ?: @"",
                                   BMS_PARAM_TAB2:ritInfo.slotID ?: @"",
                                   BMS_PARAM_TAB3:ritInfo.ecpm ?: @""}
                           dType:BMS_DTYPE_AD_ACTION
                            desc:BMS_WDS_AD_FINISH
                         options:[WDGroMoreTrackManager trackOptionsOnlySendBMS]];
    if (!error) {
//        [[WDGroMoreBmsReportManager manager] intersititialBmsEventWithEventName:BMS_EVENT_ad_show_end intersititialAd:intersititialAd];
    } else {
//        [[WDGroMoreBmsReportManager manager] intersititialBmsEventWithEventName:BMS_EVENT_ad_show_fail intersititialAd:intersititialAd];
    }
    if ([WDGroMoreDelegateManager manager].delegate &&
        [[WDGroMoreDelegateManager manager].delegate respondsToSelector:@selector(WDGroMoreIntersititialAdDidPlayFinish:didFailWithError:)]) {
        [[WDGroMoreDelegateManager manager].delegate WDGroMoreIntersititialAdDidPlayFinish:intersititialAd didFailWithError:error];
    }
}

- (void)nativeExpressFullscreenVideoAdDidShowFailed:(BUNativeExpressFullscreenVideoAd *_Nonnull)intersititialAd error:(NSError *_Nonnull)error {
    NSLog(@"❌ [Interstitial] Show failed: %@", error.localizedDescription);
    if ([WDGroMoreDelegateManager manager].delegate &&
        [[WDGroMoreDelegateManager manager].delegate respondsToSelector:@selector(WDGroMoreIntersititialAdDidShowFailed:error:)]) {
        [[WDGroMoreDelegateManager manager].delegate WDGroMoreIntersititialAdDidShowFailed:intersititialAd error:error];
    }
}

@end
